using System;
using System.Windows;
using System.Windows.Media;

namespace VisualTreeInspector
{
    /// <summary>
    /// Represents a class containing helper methods for the
    /// Inspector class. Cannot be inherited.
    /// </summary>
    public static class InspectorHelpers
    {
        /// <summary>
        /// Returns a constant zero point.
        /// </summary>
        public static Point Zero
        {
            get
            {
                return _Zero;
            }
        }

        /// <summary>
        /// Holds a point that is 0,0.
        /// </summary>
        private static Point _Zero = new Point(0, 0);

        /// <summary>
        /// Gets the absolute position of the given FrameworkElement
        /// relative to the Application RootVisual.
        /// </summary>
        /// <param name="visual">The visual to get co-ordinates for.</param>
        /// <returns>Returns the position of the visual element.</returns>
        public static Point GetPositionAbsolute(FrameworkElement visual)
        {
            MatrixTransform globalTransform = visual.TransformToVisual(Application.Current.RootVisual) as MatrixTransform;
            Point p = globalTransform.Matrix.Transform(InspectorHelpers.Zero);
            return p;
        }

        /// <summary>
        /// Returns a given DependencyObject in the visual tree, starting
        /// at the root given, by the hashcode given.
        /// </summary>
        /// <param name="root">Where to start the search.</param>
        /// <param name="hash">The hashcode to search for.</param>
        /// <returns>Returns the DependencyObject matching the hashcode
        /// given, else it returns null if the given hash could not be
        /// found.</returns>
        public static DependencyObject FindElementByHashCode(DependencyObject root, int hash)
        {
            if (root.GetHashCode() == hash)
                return root;

            int numChildren = VisualTreeHelper.GetChildrenCount(root);

            if (numChildren == 0)
                return null;

            for (int i = 0; i < numChildren; i++)
            {
                DependencyObject possibleMatch = FindElementByHashCode(VisualTreeHelper.GetChild(root, i), hash);
                if (possibleMatch != null)
                    return possibleMatch;
            }

            return null;
        }

    }
}
